function parseFileList(filelist) {
  const elems = Array.from(filelist)
  return elems.map(i => {
    // file
    return {
      file: i,
      name: i.name,
      size: parseFileSize(i.size),
      lastModified: i.lastModified,
      lastModifiedDate: i.lastModifiedDate,
      type: i.type,
      webkitRelativePath: i.webkitRelativePath,
      path: i.webkitRelativePath,
      uploadProgress: 0,
    }
  })
}

function parseFolderInfo(fileList) {
  const fileInfoItem = fileList[0]
  const folderName = fileInfoItem.path.split('/')[0]

  return {
    folderName,
  }
}

const UselessFileName = [
  '.DS_Store',
]
// 过滤无用的文件
function filterUselessFile(fileList) {
  if (!fileList) return []
  return fileList.filter(f => {
    return UselessFileName.indexOf(f.name) === -1
  })
}

const K = 1024
const KB = K
const MB = K * K
const GB = K * K * K
function parseFileSize(size) {
  if (!size) return size
  if (size < KB) return `${size}B`
  if (size < MB) return `${(size / KB).toFixed(2)}KB`
  if (size < GB) return `${(size / MB).toFixed(2)}MB`
  return `${(size / GB).toFixed(2)}GB`
}

function parseSketchMeasureHTML(htmlFile) {
  return readFileContent(htmlFile).then(res => {
    const htmlContent = res.reader.result
    const htmlContentList = htmlContent.split('\n')

    // 查找到JSON一行
    const jsonConfigRow = htmlContentList.find(i => {
      return i.indexOf('$(function(){ SMApp({') === 0
    })
    let rawJSONstring = jsonConfigRow.replace('$(function(){ SMApp(', '')
    const TAIL = ') });'
    rawJSONstring = rawJSONstring.substr(0, rawJSONstring.length - TAIL.length)
    return {
      content: rawJSONstring,
    }
  })
}

function readFileContent(fileItem) {
  if (!fileItem) return

  return new Promise((resolve, reject) => {
    const fr = new FileReader()
    fr.readAsText(fileItem)
    fr.onload = ev => {
      resolve({
        event: ev,
        reader: fr,
      })
    }
  })
}
